/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hylanda.processors.jin;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.nifi.annotation.behavior.CustomUiPreferred;
import org.apache.nifi.annotation.behavior.ReadsAttribute;
import org.apache.nifi.annotation.behavior.ReadsAttributes;
import org.apache.nifi.annotation.behavior.WritesAttribute;
import org.apache.nifi.annotation.behavior.WritesAttributes;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.processor.AbstractProcessor;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.ProcessorInitializationContext;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.processor.util.StandardValidators;

import com.alibaba.fastjson.JSONObject;
import com.hylanda.reidx4.tools.HLNifiTools;

@CustomUiPreferred
@Tags({"按规则修正字段内容"})
@CapabilityDescription("按规则修正字段内容")
@SeeAlso({})
@ReadsAttributes({@ReadsAttribute(attribute="", description="")})
@WritesAttributes({@WritesAttribute(attribute="", description="")})
public class JinUpdateValue extends AbstractProcessor {
	
	public final PropertyDescriptor RuleJson = new PropertyDescriptor
            .Builder().name("ruleJson")
            .displayName("修正规则")
            .description("根据配置的规则条件，修正某字段的内容，如：当url包含weib.com时，media_name修正为新浪微博；或当url包含httphttp时，将url中的httphttp替换为http")
            .required(true)
            .customUI(true)
            .addValidator(StandardValidators.NON_EMPTY_VALIDATOR)
            .build();

	public static final Relationship RELATIONSHIP_OK = new Relationship.Builder().name("成功").description("成功").build();
	
	private List<PropertyDescriptor> descriptors;
	
    private Set<Relationship> relationships;
    
    //页面可以添加类中没有定义的PropertyDescriptor属性
	@Override
	protected PropertyDescriptor getSupportedDynamicPropertyDescriptor(final String propertyDescriptorName) {
		PropertyDescriptor.Builder propertyBuilder = new PropertyDescriptor.Builder().name(propertyDescriptorName)
				.required(false).addValidator(StandardValidators.NON_EMPTY_VALIDATOR).dynamic(true);
		return propertyBuilder.build();
	}
    
    @Override
    protected void init(final ProcessorInitializationContext context) {
    	final List<PropertyDescriptor> descriptors = new ArrayList<PropertyDescriptor>();
    	descriptors.add(RuleJson);
		this.descriptors = Collections.unmodifiableList(descriptors);
		
        final Set<Relationship> relationships = new HashSet<Relationship>();
        relationships.add(RELATIONSHIP_OK);
        this.relationships = Collections.unmodifiableSet(relationships);
    }

    @Override
    public Set<Relationship> getRelationships() {
        return this.relationships;
    }

    @Override
    public final List<PropertyDescriptor> getSupportedPropertyDescriptors() {
        return descriptors;
    }

    @OnScheduled
    public void onScheduled(final ProcessContext context) {
    }

    @Override
    public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    	
    	FlowFile flowFile = session.get();
        if ( flowFile == null ) {
            return;
        }
        
 		try {
 			// 获取语料
 			Map<String, String> inputDataMap = HLNifiTools.sessionToMap(session, flowFile);
 			if (inputDataMap == null || inputDataMap.isEmpty()) {
 				return;
 			}
 			
 			// 修改规则
 	        String ruleJsonStr = context.getProperty(RuleJson).getValue();
 	        // {if:{field:source_type, rule:contains, val:httphttp}, then:{field:source_type, rule:equals, val:5}}
 	        // {if:{field:url, rule:contain, val:httphttp}, then:{field:url, rule:replace, val:{httphttp:http,...}} }
 	        JSONObject ruleJson = JSONObject.parseObject(ruleJsonStr);
 	        
 	        JSONObject ifJson = ruleJson.getJSONObject("if");
 	        String ifField = ifJson.getString("field");
 	       
 	        if( inputDataMap.containsKey(ifField) ){
 	    	   
 	        	JSONObject thenJson = ruleJson.getJSONObject("then");
 	        	String thenField = thenJson.getString("field");
 	        	String thenRule = thenJson.getString("rule");
 	        	String thenVal = thenJson.getString("val");
 	    	   
 	        	String ifRule = ifJson.getString("rule");
 	        	String ifVal = ifJson.getString("val");
 	        	
 	        	if(ifRule.equals("contains")){
 	        		
 	        		boolean bln = false;
 	        		if(ifVal.length()==1 && ifVal.equals(",")){
 	        			if( inputDataMap.get(ifField).contains(ifVal) ){
 	        				bln = true;
 	        			}
 	        		}
 	        		else{
 	        			String[] ifValArr = ifVal.split(",");
 	 	        		for(String str : ifValArr){
 	 	        			if( inputDataMap.get(ifField).contains(str) ){
 	 	        				bln = true;
 	 	        				break;
 	 	        			}
 	 	        		}
 	        		}
 	        		
 	        		if( bln ){
 	        			
 	        			if(thenRule.equals("equals")){
 	        				inputDataMap.put(thenField, thenVal);
 	        			}
 	        			else if(thenRule.equals("replace")){
 	        				
 	        				JSONObject thenValJson = JSONObject.parseObject(thenVal);
 	        				if( inputDataMap.containsKey(thenField) ){
 	        					
 	        					String thenFieldVal = inputDataMap.get(thenField);
 	        					for(String key : thenValJson.keySet()){
 	        						thenFieldVal = thenFieldVal.replace(key, thenValJson.getString(key));
 	        					}
 	        					inputDataMap.put(thenField, thenFieldVal);
 	        				}
 	        			}
 	        		}
 	        	}
 	        }
 	       
 	        flowFile = HLNifiTools.writeToSession(inputDataMap, session, flowFile);
 	        session.transfer(flowFile, RELATIONSHIP_OK);
 	          
 	        getLogger().billing(flowFile.getAttribute(CoreAttributes.UUID.key()));
 		} 
 		catch (UnsupportedEncodingException e) {
 			e.printStackTrace();
 		}
 		
    }
}
